package com.yuebook.smartrpc.framework.helper;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

/**
 * @author honglei
 * @date 2018/11/17 下午11:36
 */
public class IPHelper {

    private static String hostIp = StringUtils.EMPTY;

    static {
        String ip = null;
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses();
                for (InterfaceAddress address : addresses) {
                    InetAddress inetAddress = address.getAddress();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) {
                        if ("127.0.0.1".equals(inetAddress.getHostAddress())) {
                            continue;
                        }
                        ip = inetAddress.getHostAddress();
                        break;
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        hostIp = ip;
    }

    public static String localIp() {
        return hostIp;
    }
}
